#include "Main.h"
#define NOMINMAX
 
App::App()
{
}
App::~App()
{
}
bool App::Init(int argc, char *argv[]){
	framework.open_framework(argc, argv);
	window = framework.open_window();
	//ConfigVariableManager::get_global_ptr()->list_variables();
	window->get_graphics_window()->get_active_display_region(0)->set_clear_color(LColorf(0, 0, 0, 1));
	if (window != (WindowFramework *)NULL)
		nout << "Opened the window successfully!\n";
	this->Buffer = new CBufferViewer(window);
	this->Buffer->enable(false);
	this->Gui = new GuiController();
	this->Player  =new PlayerController();
	this->world = new World(this->window,this->Gui,this->Player);
	this->Gui->create_pointer(this->world);
	this->Gui->InitRocket(false);
	this->Gui->main_menu(true);
	this->Update();
	return 1;
}
bool App::Play(){
	this->Gui->hide_main_menu();
	world->LoadPhysics();
	world->LoadMap("Test");
	world->InitInput();
	Player->InitPlayer(this->world);
	world->state = "Playing";
    window->enable_keyboard(); 
	return 1;
}
string convertInt(int number)
{
   stringstream ss;//create a stringstream
   ss << number;//add number to the stream
   return ss.str();//return a string with the contents of the stream
}
bool App::Update(){
	Thread *current_thread = Thread::get_current_thread();
	ClockObject *co = ClockObject::get_global_clock();
	while(true){
		if(this->world->state == "Playing"){
			if(!world->Update())
				return false;
			if(!world->check_input())
				return false;
			if(!Player->Update())
				return false;
		}
		if(this->world->state == "Play")
			this->Play();
		if(this->world->state == "Exit")
			return false;
		WindowProperties newP = window->get_graphics_window()->get_properties();
		newP.set_title(convertInt(co->get_average_frame_rate()));//convertInt(1/(co->get_average_frame_rate()get_dt())));
		window->get_graphics_window()->request_properties(newP);
		if(!framework.do_frame(current_thread))
			return false;
	}
	#ifdef HAVE_ROCKET_PYTHON
    Py_Finalize();
	#endif
  framework.close_framework();
  return true;
}
//INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
int main(int argc, char *argv[])
    {
		load_prc_file("./config/Config.prc");
		//CSplashScreen::ShowSplashScreen( NULL, " ", 2000);
		//Sleep(2000);
		std::ostream *no = new fstream;
		//Notify::ptr()->set_ostream_ptr(no,0);
        App a;
        try {
			a.Init(__argc,__argv);
        } catch(...) {
            MessageBox( NULL,"Error", "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
        }
        return 0;
    }